<?php

namespace app\middleware;

use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;
use ReflectionClass;
use ReflectionMethod;

use Webman\Exception\BusinessException;

class AnnotationAuthMiddleware implements MiddlewareInterface
{
    public function process( Request $request , callable $handle) : Response
    {
        $controller =   $request -> controller;
        $action     =   $request -> action;

        try {
            $classRef   =   new ReflectionClass($controller);
            $methodRef  =   new ReflectionMethod($controller , $action);

            // 检查权限注解

            $this->checkPermission($classRef , $methodRef , $request);
        } catch (\Exception $e)
        {
            throw new BusinessException($e->getMessage() , '403');
        }


        return $handle($request);
    }


    private  function checkPermission(ReflectionClass $class , ReflectionMethod $method , Request $request )
    {
        $classAuth      =   $class  ->  getAttributes('IsPermission');
        $methodAuth     =   $method ->  getAttributes('IsPermission');

        if (!empty($classAuth) || !empty($methodAuth))
        {
            // 验证权限逻辑
        }

//        throw new \Exception('无权限访问');
    }
}